import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { message } from 'antd';
import { useParams, useHistory } from 'react-router-dom';
import MonitorChart from './MonitorChart';

interface DAC {
  connected: boolean;
  name: string;
  unit: string;
  samplesPerSecond: number;
}

const DacMonitor = () => {
  let [dacInfos, setDacInfos] = useState([]);
  let { deviceName } = useParams();
  let history = useHistory();

  useEffect(() => {
    axios
      .get('/dacs', {
        params: {
          deviceName
        }
      })
      .then((response) => {
        setDacInfos(response.data);
      })
      .catch((error) => {
        if (error.response?.status === 401) {
          message.error('请先登录！');
          history.replace('/login');
        }
      });
  }, [deviceName, history]);

  return (
    <div>
      {dacInfos.map((dac: DAC) => (
        <MonitorChart
          key={dac.name}
          connected={dac.connected}
          name={dac.name}
          unit={dac.unit}
          samplesPerSecond={dac.samplesPerSecond}
          maxPointsInDynamicGraph={200}
          detailedPointsCount={100}
          detailedPointsMoveSteps={20}
        />
      ))}
    </div>
  );
};

export default DacMonitor;
